// request.js

// 设置主机 URL
function setHostUrl(host) {
    localStorage.setItem("hostUrl", host);
}

// 获取主机 URL
function getHostUrl() {
    return localStorage.getItem("hostUrl");
}

// 设置令牌
function setToken(tokenName, tokenValue) {
    localStorage.setItem(tokenName, tokenValue);
}

// 获取令牌
function getToken(tokenName) {
    return localStorage.getItem(tokenName);
}

// 登录函数
function Login(username, password,type) {
    return new Promise((resolve, reject) => {
        const host = getHostUrl();
        const url = `${host}/user/login`;
        const data = { username, password,type };
        
        fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json',"Accept": "*/*" },
                body: JSON.stringify(data),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
            
                return response.json();
            
            })
            .then(  async (result) => {
            
                setToken("refreshToken", result.data.refreshToken);
                if(result.code === 200){
                    await RefreshToken(result.data.refreshToken)
                }
                resolve(result)
                }
                
            )
            .catch(reject);
    });
}

// 刷新令牌函数
function RefreshToken(refreshToken) {
    return new Promise((resolve, reject) => {
        const host = getHostUrl();
        const url = `${host}/user/refreshToken`;
        
        fetch(url, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json', 'RefreshToken': refreshToken },
               
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
            
                return response.json();
            
            })
            .then(  (result) => {
                if(result.code === 200){
                    setToken("accessToken", result.data.accessToken);
                    if(result.data.refreshToken){
                        setToken("refreshToken", result.data.refreshToken);
                    }
                }else if(result.code === 419){
                    localStorage.removeItem("accessToken");
                    localStorage.removeItem("refreshToken");
                    alert("登录已过期，请重新登录");
                }
                resolve(result);
            })
            .catch(reject);
    });
}

function register(nickname,username, password) {
    return new Promise((resolve, reject) => {
        const host = getHostUrl();
        const url = `${host}/user/register`;
        const data = {nickname,username, password,type:1 };
        
        fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
            
                return response.json();
            
            })
            .then(resolve)
            .catch(reject);
    });
}

// 处理响应
function handleResponse(response) {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json();
}

// 发送 GET 请求的函数
function Get(url) {
    return new Promise((resolve, reject) => {
        const host = getHostUrl();
        url = `${host}${url}`;
        const accessToken = getToken("accessToken");

        fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',

                    'Authorization': accessToken,
                },
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
            
                return response.json();  //转换为json格式
            
            })
            .then((result) => {
                if(result.code === 402){
                    RefreshToken(getToken("refreshToken")).then((result) => {
                        if(result.code === 200){
                            Get(url).then(resolve).catch(reject);
                        }
                    }).catch(reject);
                }
                resolve(result);
            })
            .catch(reject);
    });
}
